package com.javaee.lpr.cotroller;

import com.javaee.lpr.service.ex.*;
import com.javaee.lpr.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {
    // 成功状态码
    public static final int OK = 200;
    @ExceptionHandler(ServiceException.class) // 异常时不用返回data，所以用void，所有报错都用这个
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>((Exception) e);
        if(e instanceof NameDuplicatedException){
            result.setState(4000);
            result.setMessage("用户名重复");
        } else if (e instanceof UserNotFoundException) {
            result.setState(5001);
            result.setMessage("用户不存在");
        }else if (e instanceof PasswordNotMatchException) {
            result.setState(5002);
            result.setMessage("密码不匹配");
        }else if (e instanceof InsertException) {
            result.setState(5000);
            result.setMessage("注册时发生未知错误");
        }else if (e instanceof UpdateException) {
            result.setState(5010);
            result.setMessage("更新数据时发生未知错误");
        }

        return result;
    }

    // session获取id
    protected final Integer getIdFormSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("id").toString());
    }
    // session获取username
    protected final String getUsernameFormSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
